import {
  Component,
  ViewChild,
  Injector,
  Output,
  EventEmitter,
  ElementRef,
} from "@angular/core";
import { ModalDirective } from "ngx-bootstrap";
import {
  PipelineServiceProxy,
  PipelineListDto,
} from "@shared/service-proxies/service-proxies";
import { AppComponentBase } from "@shared/common/app-component-base";

import { finalize } from "rxjs/operators";
import { LazyLoadEvent } from "primeng/primeng";

@Component({
  selector: "actAbnormalModal",
  templateUrl: "./act-abnormal-modal.component.html",
})
export class ActAbnormalModalComponent extends AppComponentBase {
  @ViewChild("actionModal") modal: ModalDirective;

  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;

  pipe: PipelineListDto = new PipelineListDto();
  event: LazyLoadEvent;
  actAbnormal = "";
  actNames = new Array<string>();

  constructor(
    injector: Injector,
    private _pipelineService: PipelineServiceProxy
  ) {
    super(injector);
  }

  show(
    pipe: PipelineListDto,
    actAbnormal: string,
    event?: LazyLoadEvent
  ): void {
    this.actAbnormal = actAbnormal;
    this.pipe = pipe;
    this.event = event;
    this.active = true;
    this._pipelineService
      .getAbnormalActIncludeComponents(actAbnormal)
      .subscribe((result) => {
        console.log(result);
        this.actNames = result.items;
        this.modal.show();
      });
  }

  save(): void {
    this.saving = true;

    this._pipelineService
      .insertAbnormalComponentByName(this.pipe.id, this.actAbnormal)
      .pipe(
        finalize(() => {
          this.close();
          this.saving = false;
        })
      )
      .subscribe((result) => {
        this.modalSave.emit(this.event);
      });
  }

  close(): void {
    this.saving = false;
    this.modal.hide();
  }
}
